package 多线程.文件查找多线程125;

/**
 * @program: Thread
 * description:
 * @author:yyq
 * @create: 2023-07-16 16:05
 */

import java.io.File;
import java.util.concurrent.ConcurrentLinkedQueue;

public class ParallelGroupFileSearch {

    public static void main(String[] args) {
        Result result = new Result();
        result.setFound(false);
        File file = new File("C:\\windows");
        long start = System.currentTimeMillis();
        ParallelGroupFileSearch.searchFiles(file,"hosts",result);
        long end = System.currentTimeMillis();
        System.out.println("多线程执行耗时： "+(end - start)+"ms");
    }

    public static void searchFiles(File file, String fileName, Result parallelResult) {
        ConcurrentLinkedQueue<File> directories = new ConcurrentLinkedQueue<>();
        File[] conients = file.listFiles();

        for (File content : conients) {
            if (content.isDirectory()) {
                directories.add(content);
            }
        }

        int numThreads = Runtime.getRuntime().availableProcessors(); //获取可用的线程数量
        Thread[] threads = new Thread[numThreads];

        ParallelGroupFileTask[] tasks = new ParallelGroupFileTask[numThreads];

        for (int i = 0; i < numThreads; i++) {   //写入数组中
            tasks[i] = new ParallelGroupFileTask(fileName, directories, parallelResult);
            threads[i] = new Thread(tasks[i]);
            threads[i].start();
            System.out.println(threads[i].getName()+"被启动了");
        }

        boolean finish = false;

        int numFinished = 0;

        while (!finish) {
            numFinished = 0;
            for (int i = 0; i < threads.length; i++) {
                if (threads[i].getState() == Thread.State.TERMINATED) {
                    numFinished++;
                    if (tasks[i].getFound()) {
                        finish = true;
                    }
                }
            }
            if (numFinished == threads.length) { //当所有的线程都执行完，则停止
                finish = true;
            }
        }

        //如果numFinished比length小，则证明查找到文件
        //取消全部进程
        if (numFinished != threads.length) {
            for (Thread thread : threads) {
                thread.interrupt();
            }
        }
    }
}

